// pages/orderDetail/orderDetail.js
import * as API_Order from '../../api/order'
import * as API_Product from '../../api/product'
import * as API_Store from '../../api/store'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: null,
    order: {},
    store: {},
    product: {},
    mainAttr: {},
    mutipleAttr: [],
    origin: -1,
    url: ''
  },
  received() {
    wx.navigateTo({
      url: '/pages/commentEdit/commentEdit?orderId=' + this.data.id,
    })
  },
  cancelpay() {
    const that = this
    wx.showModal({
      title: '提示',
      content: '确定取消订单？',
      success() {
        API_Order.cancelOrder({orderId: that.data.id}).then(res => {
          if(res.code == 200) {
            wx.showToast({
              title: '取消成功',
            })
            setTimeout(function() {
              wx.navigateBack({
                delta: 1
              })
            },500)

          } else {
            wx.showToast({
              title: '取消失败',
            })
          }

        })
      }
    })
  },
  formatTime(val) {
    const date = new Date(val)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : '0' +(date.getMonth() + 1)
    const day = date.getDate() > 0 ? date.getDate() : '0' + date.getDate()
    const h = date.getHours()
    const m = date.getMinutes()
    const s = date.getSeconds()
    return year + '-' + month + '-' + day + ' ' + h + ':' + m + ':' + s
  },
  pay() {
    let orderId = this.data.id;
    let params = {
      orderId: orderId
    }
    API_Order.delayPay(params).then(res => {
      if (res.code == 200) {
        let payment = res.data;
        if (payment.status == "succeeded") {
          let expend = payment.expend;
          let pay_info = JSON.parse(expend.pay_info);
          wx.requestPayment({
            'timeStamp': pay_info.timeStamp,
            'nonceStr': pay_info.nonceStr,
            'package': pay_info.package,
            'signType': pay_info.signType,
            'paySign': pay_info.paySign,
            'success': function (res) {
              wx.showToast({
                title: '支付成功',
              })
              this.loadData()
            },
            'fail': function (res) {},
            'complete': function (res) {}
          })
        }
      } else {
        wx.showToast({
          title: res.msg
        })
      }
    })
  },
  goStore(e) {
    let id = this.data.store.id
    wx.navigateTo({
      url: '/pages/storeHome/storeHome?id=' + id,
    })
  },
  applyRefund(e) {
    wx.navigateTo({
      url: '../refundApply/refundApply?orderId=' + e.currentTarget.dataset.id,
    })
  },

  // goStore(e){
  //   debugger
  //   wx.navigateTo({
  //     url: '/pages/storeHome/storeHome?id='+e.currentTarget.dataset.id,
  //   })
  // },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let globalData = getApp().globalData;
    let windowHeight = globalData.windowHeight;
    let navHeadHeightpx = globalData.navHeadHeightpx;
    this.setData({
      navHeadHeightpx: navHeadHeightpx,
      windowHeight: windowHeight,
      origin: options.origin
    });
    if(options.origin == 1) {
      this.setData({
        url: '/pages/myOrderList/myOrderList?orgin=1' 
      })
    }
    console.log(options.id)
    this.data.id = parseInt(options.id)
  },
  loadData() {
    let that = this
    API_Order.getOrder(this.data.id).then(res => {
      let order = res.data;
      console.log(order)
      order.refundApplyTime = order.refundApplyTime ? that.formatTime(order.refundApplyTime) : ''
      if (order) {
        let verifyCode = order.verifyCode;
        if (verifyCode) {
          if (verifyCode.length > 4) {
            let q = verifyCode.substring(0, 4);
            let h = verifyCode.substring(4);
            order.verifyCode = q + " " + h;
          }
        }
        let aftersaleCode = order.aftersaleCode;
        if (aftersaleCode) {
          if (aftersaleCode.length > 4) {
            let q = aftersaleCode.substring(0, 4);
            let h = aftersaleCode.substring(4);
            order.aftersaleCode = q + " " + h;
          }
        }
        order.showComment = true
        switch (order.orderState) {
            case 'wait_use':
              order.orderMsg = '待使用'
              order.showComment = false
              break
            case 'wait_pay':
              order.orderMsg = '待付款'
              order.showComment = false
              break
            case 'used':
              if (order.writeOffNum > 0) {
                order.orderMsg = '待使用'
              } else {
                order.orderMsg = '已完成'
              }
              if (order.commentState == 'Y') {
                order.showComment = false
              }
              break
            case 'order_close':
              order.orderMsg = '已完成'
              order.showComment = false
              break
            case 'received':
              order.orderMsg = '待评价'
              break
            case 'aftersale':
              order.orderMsg = '待售后'
              order.showComment = false
              break
            case 'refund_success':
              order.orderMsg = '退款成功'
              break
          }
        // if (order.aftersaleState == 'Y') {
        if (order.orderState == 'refund_apply') {
          order.showComment = false
          order.orderMsg = '退款中'
          switch (order.refundStatus) {
            case 'apply':
              order.refundMsg = '退款中'
              order.orderMsg = '退款中'
              break
            case 'pass':
              order.refundMsg = '退款中'
              order.orderMsg = '退款中'
              break
            case 'refunding':
              order.refundMsg = '退款中'
              order.orderMsg = '退款中'
              break
            case 'refused':
              order.refundMsg = '拒绝退款'
              order.orderMsg = '拒绝退款'
              break
            case 'success':
              order.refundMsg = '退款成功'
              order.orderMsg = '退款成功'
              break
          }
        }

        // if (order.aftersaleState == 'N') {
        //   switch (order.orderState) {
        //     case 'wait_use':
        //       order.orderMsg = '待使用'
        //       order.showComment = false
        //       break
        //     case 'wait_pay':
        //       order.orderMsg = '待付款'
        //       order.showComment = false
        //       break
        //     case 'used':
        //       if (order.writeOffNum > 0) {
        //         order.orderMsg = '待使用'
        //       } else {
        //         order.orderMsg = '已完成'
        //       }
        //       if (order.commentState == 'Y') {
        //         order.showComment = false
        //       }
        //       break
        //     case 'order_close':
        //       order.orderMsg = '已完成'
        //       order.showComment = false
        //       break
        //     case 'received':
        //       order.orderMsg = '待评价'
        //       break
        //     case 'aftersale':
        //       order.orderMsg = '待售后'
        //       order.showComment = false
        //       break
        //   }
        // }

        this.setData({
          order: order,
        })
        getApp().https.ajax({
          method: 'post',
          url: '/product/getInfo',
          data: {
            id: res.data.productId,
            storeId: res.data.storeId
          },
          loading: true
        }).then(res => {
          let arr = []
          let mainArr = []
          let item = JSON.parse(res.data.itemDetail)
          for (var i = 0; i < item.length; i++) {
            let attr = item[i]
            if (attr.type == 'mainAttr') {
              mainArr.push(attr)
            }
            if (attr.type == 'multipleAttr') {
              arr.push(attr)
            }
          }
          res.data.useStartTime = res.data.useStartTime.replaceAll('-', '.')
          res.data.useEndTime = res.data.useEndTime.replaceAll('-', '.')
          that.setData({
            product: res.data,
            mutipleAttr: arr,
            mainAttr: mainArr
          })
          this.choicePeopleGuige = this.selectComponent("#peopleArray")
          let r = {
            key: 'jy_people_right',
            title: '',
            selected: res.data.peopleRight
          }
          this.choicePeopleGuige.loadDic(r)
        })
        // wxbarcode.qrcode('qrcode',res.data.verifyCode,300,300)
        // API_Product.getTemp(res.data.productBackId).then(res => {
        //   let arr = []
        //   let mainArr = []
        //   let item = JSON.parse(res.data.itemDetail)
        //   for (var i = 0; i < item.length; i++) {
        //     let attr = item[i]
        //     if (attr.type == 'mainAttr') {
        //       mainArr.push(attr)
        //     }
        //     if (attr.type == 'multipleAttr') {
        //       arr.push(attr)
        //     }
        //   }
        //   that.setData({
        //     product: res.data,
        //     mutipleAttr: arr,
        //     mainAttr: mainArr
        //   })
        //   this.choicePeopleGuige = this.selectComponent("#peopleArray")
        //   let r = {
        //     key: 'jy_people_right',
        //     title: '',
        //     selected: res.data.peopleRight
        //   }
        //   this.choicePeopleGuige.loadDic(r)
        //   // this.choiceServiceGuige = this.selectComponent("#service")
        //   let e = {
        //     key: 'jy_service_item',
        //     title: '',
        //     selected: res.data.service
        //   }
        //   // this.choiceServiceGuige.loadDic(e)
        // })
      }
      API_Store.getInfo(res.data.storeId).then(res => {
        that.setData({
          store: res.data
        })
      })
    })
  },
  goRefund(e) {
    wx.navigateTo({
      url: '/pages/refundDetail/refundDetail?id=' + e.currentTarget.dataset.id,
    })
  },
  viewImg(e) {
    let a = e.currentTarget.dataset.src
    let src = []
    src[0] = a
    wx.previewImage({
      current: src[0],
      urls: src,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.loadData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  callPhone() {
    let that = this
    wx.makePhoneCall({
      phoneNumber: that.data.store.storePhone + ''
    })
  },
  openMap() {
    let that = this
    wx.openLocation({
      latitude: that.data.store.latitude * 1, //纬度
      longitude: that.data.store.longitude * 1, //经度
      name: that.data.store.location, //目的地定位名称
      scale: 15, //缩放比例
      address: that.data.store.addressName //导航详细地址
    })
  },
})